package com.example.warehousems.service;

import com.example.warehousems.dao.ActivityRepository;
import com.example.warehousems.dao.model.Activity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ActivityService {
    @Autowired
    private ActivityRepository activityRepository;

    // 获得所有用户的未读的消息
    public List<Activity> getAll() {
        return activityRepository.findAllByIsReadOrderByTimeDesc(0);
    }

    // 获得对应用户的未读的消息
    public List<Activity> getAll(Integer userId) {
        return activityRepository.findByUserIdAndIsReadOrderByTimeDesc(userId, 0);
    }

    public Page<Activity> getAllByUserId(int userId, Pageable pageable) {
        return activityRepository.findByUserId(userId, pageable);
    }

    public Page<Activity> getAll(Pageable pageable) {
        return activityRepository.findAll(pageable);
    }

    public void addActivity(Integer userId, String title, String description) {
        var activity = new Activity();
        activity.setUserId(userId);
        activity.setTitle(title);
        activity.setDescription(description);
        activity.setTime(new java.util.Date().toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDateTime());
        activityRepository.save(activity);
    }

    public void markAllAsRead(Integer userId, int[] ids) {
        var activities = activityRepository.findByIdIn(ids);
        for (var activity : activities) {
            if (!activity.getUserId().equals(userId)) {
                continue;
            }
            activity.setIsRead(1);
            activityRepository.save(activity);
        }
    }
}
